package eerbaar.v2.app.strategy;

import eerbaar.client.ctr.IGameController;
import eerbaar.client.ctr.IGameControllerFactory;
import eerbaar.client.ctr.OperatorConstants;
import eerbaar.game.IGame;
import eerbaar.memory.IMemory;
import eerbaar.persona.IPersona;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;
import eerbaar.v2.app.mover.IPersonaMover;

public class FreePlayStrategy implements IPersonaStrategy {

    private final IPersona subject;

    public FreePlayStrategy(IPersona subject) {
        this.subject = subject;
    }

    private String calcProgram() {

        IMemory memory = this.subject.getHead().getBrain().getMemory();
        INode ideas = memory.getIdeaNode();
        INode priority = memory.getIdeaPriorityNode();
        INode pattern = memory.getIdeaPatternNode();

        String program = "";
        INode[] children = ideas.getChildren();
        for (INode node : children) {

            String key = node.getPayload().getKey();
            String value = node.getPayload().getValue();

            int numeric = 5;
            INode pNode = NodeCmdFactory.findChild(priority, key);
            if (pNode != null) {
                numeric = pNode.getAttributes().get(Integer.class, "pri");
            }

            int numericPattern = 0;
            INode patternNode = NodeCmdFactory.findChild(pattern, key);
            if (patternNode != null) {
                numericPattern = patternNode.getAttributes().get(Integer.class,
                        "pri");
            }

            value = clean(value);

            program += " ( " + numeric + " " + numericPattern + " " + value
                    + " ) ";
        }

        if (program.length() > 0) {
            program += " ( persona -- ) " + OperatorConstants.ADD;
        }

        return program;
    }

    private String clean(String value) {
        value = value.replace('(', ' ');
        value = value.replace(')', ' ');
        value = value.trim();
        return value;
    }

    public boolean isAvailable() {
        String program = calcProgram();
        return (program.length() > 0);
    }

    @Override
    public boolean move(IPersonaMover mover, IGame game) {

        boolean finished = true;

        String program = calcProgram();

        if (program.length() > 0) {
            IGameControllerFactory factory = ServiceFactory
                    .getService(IGameControllerFactory.class);
            IGameController controller = factory.create(this.subject, game);

            finished = controller.input(program);
        }

        return !finished;
    }

}
